import { Button, NavBar, Form, Input, List, Toast } from 'antd-mobile'
import styles from './index.module.scss'
import { useHistory } from 'react-router'
import { LoginForm } from '@/types/data'
import { useDispatch } from 'react-redux'
import { loginAction } from '@/store/actions/login'
import { AxiosError } from 'axios'

const Login = () => {
  const history = useHistory()
  const dispatch = useDispatch()
  // 校验通过
  const onFinish = (values: LoginForm) => {
    // console.log(values)
    try {
      dispatch(loginAction(values))
      // 提示
      Toast.show({
        icon: 'success',
        content: '登录成功',
        duration: 600,
        afterClose: () => {
          // 返回首页
          history.push('/home')
        },
      })
    } catch (e) {
      const error = e as AxiosError<{ message: string }>
      Toast.show({
        content: error.response?.data.message,
        duration: 1000,
      })
    }
  }
  // 校验失败
  const onFinishFailed = (errorInfo: any) => {
    console.log(errorInfo)
  }
  return (
    <div className={styles.root}>
      <NavBar onBack={() => history.go(-1)}></NavBar>

      <div className='login-form'>
        <h2 className='title'>账号登录</h2>

        <Form
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          initialValues={{
            mobile: '13911111111',
            code: '246810',
            remember: true,
          }}
        >
          <Form.Item
            className='login-item'
            name='mobile'
            rules={[
              { required: true, message: '请输入手机号' },
              {
                pattern:
                  /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
                message: '手机号格式不正确！',
                validateTrigger: 'onBlur',
              },
            ]}
          >
            <Input placeholder='请输入手机号' />
          </Form.Item>
          <List.Item
            className='login-code-extra'
            extra={<span className='code-extra'>发送验证码</span>}
          >
            <Form.Item
              name='code'
              className='login-item'
              rules={[
                { required: true, message: '请输入验证码！' },
                { len: 6, message: '验证码6个字符', validateTrigger: 'onBlur' },
              ]}
            >
              <Input placeholder='请输入验证码' autoComplete='off' />
            </Form.Item>
          </List.Item>

          <Form.Item noStyle>
            <Button
              block
              type='submit'
              color='primary'
              className='login-submit'
            >
              提交
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}
export default Login
